<template>
  <ych-modal
    :fullscreen="false"
    :title="title"
    :visible="visible"
    :loading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
    :cancelText="$t('m.common.button.close')">
    <a-button-group style="margin-bottom: 8px;">
      <a-button icon="plus" @click="handleAdd" type="primary">{{$t('m.bpm.other.custom_button')}}</a-button>
    </a-button-group>
    <a-table
      size="small"
      bordered
      rowKey="id"
      :columns="columns"
      :pagination="false"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: getCheckboxProps, onSelect: onSelect}"
      :dataSource="data">
      <template slot="alias" slot-scope="text, record">
        <ych-editable-cell v-if="visible" :text="text" @change="onCellChange(record.id, 'alias', $event)"/>
      </template>
      <template slot="type" slot-scope="text, record">
        <ych-editable-cell v-if="record.custom" :text="text" @change="onCellChange(record.id, 'type', $event)"/>
        <span v-if="!record.custom">{{record.type}}</span>
      </template>
      <template slot="mustIdea" slot-scope="text, record">
        <ych-editable-cell v-if="visible && (disableEditIdea.indexOf(record.id) == -1)" :text="text" type="select"
                           :select-data="selectData"
                           @change="onCellChange(record.id, 'mustIdea', $event)"/>
        <span v-if="disableEditIdea.indexOf(record.id) != -1">{{$t('m.bpm.design.idea_can_be_left_blank')}}</span>
      </template>
      <template slot="order" slot-scope="num, record">
        <ych-editable-cell v-if="record.custom" type="number" :num="num"
                           @change="onCellChange(record.id, 'order', $event)"/>
        <span v-if="!record.custom">{{record.order}}</span>
      </template>
      <template slot="icon" slot-scope="text, record">
        <ych-editable-cell v-if="record.custom" :text="text" @change="onCellChange(record.id, 'icon', $event)"/>
        <ych-icon v-if="record.icon" :type="record.icon"></ych-icon>
        <span v-if="!record.custom">{{record.icon}}</span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a-popconfirm
          v-if="record.custom"
          :title="$t('m.common.tip.delete_confirm')"
          @confirm="() => onDelete(record.id)"
        >
          <a href="javascript:;">{{ $t('m.common.button.delete') }}</a>
        </a-popconfirm>
        <a-divider v-if="record.custom" type="vertical"/>
        <a-badge
          :dot="!!(record.attribute.afterProcessingBean || record.attribute.afterProcessingGroovy || record.attribute.taskPressTodoEmail || record.attribute.taskPressTodoPhone || record.attribute.addPassRound || record.attribute.submitToRejectNode)">
          <a @click="editAttribute(record)">{{ $t('m.bpm.design.property') }}</a>
        </a-badge>
      </template>
    </a-table>

    <ych-modal
      :fullscreen="false"
      size="middle"
      :title="attribute_title"
      :visible="attribute_visible"
      @ok="attribute_handleOk"
      @cancel="attribute_handleCancel">
      <template slot="footer">
        <a-button key="submit" type="primary" @click="attribute_handleOk">{{ $t('m.common.button.ok') }}</a-button>
      </template>
      <a-form>
        <a-form-item :label="$t('m.bpm.design.press_type')" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="currentRecord.id == 'pressTodo'">
          <a-checkbox v-model="currentRecord.attribute.taskPressTodoEmail">{{$t('m.bpm.design.press_type_mail')}}</a-checkbox>
          <a-checkbox v-model="currentRecord.attribute.taskPressTodoPhone">{{$t('m.bpm.design.press_type_sms')}}</a-checkbox>
          <!--<a-checkbox v-model="currentRecord.attribute.taskPressTodoWeixin">微信</a-checkbox>-->
        </a-form-item>
        <a-form-item :label="$t('m.bpm.design.passRound')" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="currentRecord.id == 'submit'">
          <a-checkbox v-model="currentRecord.attribute.addPassRound">{{$t('m.bpm.design.enable_add_passRound')}}</a-checkbox>
        </a-form-item>
        <a-form-item :label="$t('m.bpm.design.other')" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="currentRecord.id == 'submit'">
          <a-checkbox v-model="currentRecord.attribute.submitToRejectNode">{{$t('m.bpm.design.enable_sendto_backnode')}}</a-checkbox>
        </a-form-item>
        <a-form-item :label="$t('m.bpm.design.specifyNode')" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="currentRecord.id == 'rejectWantTask'">
          <a-select v-model="currentRecord.attribute.taskScope" @change="handleUserTaskChange"
                    mode="multiple"
                    :placeholder="$t('m.bpm.design.specifyNodePlaceholder')">
            <a-select-option v-for="userTask in userTasks" :key="userTask.id">
              {{userTask.name}}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="currentRecord.id && currentRecord.id !== 'setInstanceUsers'" :label="$t('m.bpm.design.after_java')" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-model="currentRecord.attribute.afterProcessingBean" :placeholder="$t('m.bpm.design.after_java_placeholder')"></a-input>
        </a-form-item>
        <a-form-item v-if="currentRecord.id && currentRecord.id !== 'setInstanceUsers'" :label="$t('m.bpm.design.after_script')" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <script-button v-model="currentRecord.attribute.afterProcessingGroovy" :label="$t('m.bpm.design.after_script_button_name')" help-code="afterProcessingForGroovy" :groovy="true"></script-button>
        </a-form-item>
      </a-form>
    </ych-modal>
  </ych-modal>
</template>

<script>

  import {getAction} from '@/api/manage';
  import YchConstant from "@/api/YchConstant";
  import {YchEditableCell} from '@yuncheng/ych-components'
  import ScriptButton from "../../../eform/modules/designer/packages/ScriptButton";

  export default {
    name: "BpmButtonList",
    components: {
      YchEditableCell,
      ScriptButton,
    },
    data() {
      return {
        title: this.$t('m.bpm.other.process_dialog'),
        visible: false,
        loading: false,
        userTasks: [],
        url: {
          getBpmButtonList: YchConstant.PREFIX_BPM + "/bpm-back/processDefRest/getBpmButtonList/v1",
        },
        defaultData: [],
        selectedRowKeys: [],
        data: [],
        global: false,
        currentRecord: {},
        selectData: [{id: '1', text: this.$t('m.bpm.design.required')}, {id: '2', text:this.$t('m.bpm.design.not_required')}],
        disableEditIdea: ['suspend', 'activate', 'setInstanceUsers', 'reStart'],
        columns: [{
          title:this.$t('m.common.label.number'),
          dataIndex: '',
          key: 'rowIndex',
          width: '8%',
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        }, {
          title: this.$t('m.bpm.design.default_name'),
          align: 'left',
          width: '14%',
          dataIndex: 'label',
        }, {
          title: this.$t('m.bpm.design.custom_name'),
          align: 'center',
          width: '12%',
          dataIndex: 'alias',
          scopedSlots: {customRender: 'alias'}
        }, {
          title: this.$t('m.bpm.design.method_name'),
          align: 'left',
          width: '20%',
          dataIndex: 'type',
          scopedSlots: {customRender: 'type'}
        }, {
          title: this.$t('m.bpm.design.idea'),
          align: 'center',
          width: '12%',
          dataIndex: 'mustIdea',
          scopedSlots: {customRender: 'mustIdea'}
        }, {
          title: this.$t('m.common.label.sort'),
          align: 'center',
          width: '7%',
          dataIndex: 'order',
          scopedSlots: {customRender: 'order'}
        }, {
          title: this.$t('m.bpm.design.icon'),
          align: 'left',
          width: '16%',
          dataIndex: 'icon',
          scopedSlots: {customRender: 'icon'}
        }, {
          title: this.$t('m.common.label.operate'),
          dataIndex: 'action',
          scopedSlots: {customRender: 'operation'},
          align: 'center',
          width: '13%'
        }],
        attribute_title: this.$t('m.bpm.design.property'),
        attribute_visible: false,
        labelCol: {
          xs: {span: 24},
          sm: {span: 4},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
      }
    },
    methods: {
      attribute_handleOk() {
        this.attribute_visible = false
      },
      attribute_handleCancel() {
        this.attribute_visible = false
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
      },
      open(json, global, userTasks) {
        this.userTasks = userTasks || []
        this.selectedRowKeys = [];
        this.global = global;
        this.currentRecord = {};
        this.data = this.defaultData.filter(item => global ? item.global : !item.global);
        if (!json) {
          json = {};
        }
        this.data.forEach(vo => {
          vo.alias = null;
          vo.mustIdea = '2';
          vo.attribute = {};
          if (json[vo.id]) {
            vo.alias = json[vo.id].alias;
            vo.mustIdea = json[vo.id].mustIdea;
            vo.attribute = json[vo.id].attribute;
            this.selectedRowKeys.push(vo.id);
          } else if (vo.id == 'submit') {
            this.selectedRowKeys.push(vo.id);
          }
        });
        Object.values(json).forEach(vo => {
          if (vo.custom) {
            this.data.push(vo);
            this.selectedRowKeys.push(vo.id);
          }
        });
        this.visible = true;
      },
      handleOk() {
        if (this.selectedRowKeys.length == 0) {
          this.$emit('selectFinished');
        } else {
          let json = {};
          let alias = "";
          let pressFlg = false;
          this.data.forEach(vo => {
            if (this.selectedRowKeys.indexOf(vo.id) != -1) {
              json[vo.id] = vo;
              alias += ((vo.alias ? vo.alias : vo.label) + '，');

              if (vo.id == 'pressTodo') {
                pressFlg = !(vo.attribute.taskPressTodoEmail || vo.attribute.taskPressTodoPhone || vo.attribute.taskPressTodoWeixin);
              }
            }
          });
          if (pressFlg) {
            this.messageUtil.warning(this.$t('m.bpm.design.press_type_blank_tips'));
            this.currentRecord = json['pressTodo'];
            return;
          }
          alias = alias.substr(0, alias.length - 1);
          this.$emit('selectFinished', alias, json);
        }
        this.handleCancel();
      },
      handleCancel() {
        this.visible = false;
      },
      onCellChange(key, dataIndex, value) {
        const data = [...this.data];
        const target = data.find(item => item.id === key);
        if (target) {
          target[dataIndex] = value;
          this.data = data;
        }
      },
      refresh() {
        const that = this;
        that.loading = true;
        getAction(this.url.getBpmButtonList, {}).then((res) => {
          if (res.success) {
            that.defaultData = res.result;
          } else {
            that.messageUtil.warning(res.message);
          }
        }).finally(() => {
          that.loading = false;
        });
      },
      getCheckboxProps: record => ({
        props: {
          disabled: record.id === 'submit' || record.custom
        }
      }),
      handleAdd() {
        const {data} = this;
        const newData = {
          id: "" + Math.random(),
          label: this.$t('m.bpm.other.custom_button'),
          alias: null,
          type: null,
          mustIdea: '2',
          order: 20,
          icon: '',
          custom: true,
          global: this.global,
          attribute: {}
        };
        this.data = [...data, newData];
        this.selectedRowKeys.push(newData.id);
      },
      onDelete(id) {
        const data = [...this.data];
        this.data = data.filter(item => item.id !== id);

        const selectedRowKeys = [...this.selectedRowKeys];
        this.selectedRowKeys = selectedRowKeys.filter(item => item !== id);
      },
      editAttribute(record) {
        this.currentRecord = record;
        this.attribute_title = this.$t('m.bpm.design.property')+"——" + (record.alias ? record.alias : record.label);
        this.attribute_visible = true
      },
      onSelect(record, selected, selectedRows, nativeEvent) {
        if (selected) {
          this.currentRecord = record;
        } else {
          this.currentRecord = {};
        }
      },
      handleUserTaskChange(value){
        //console.log(`Selected: ${value}`);
      }
    },
    mounted() {
      this.refresh();
    }
  }
</script>
